'use strict'

define(function (require, exports, module) {
    var angular = require('angular');
    var dialog = require("dialogplus");
    require("/public/js/plugins/select2/select2");
    var util = require("util");
    var api_prefix = G_CONFIG["api_prefix"]; //api前缀
    require('/public/js/myservice/contract/contract-common');
    var myMath = require('/public/js/myservice/common/my-math');

    var ContractReceivableRefund = angular.module('ContractReceivableRefund', ['ContractCommonService']);
    ContractReceivableRefund.service('confirmRefundService', ['$rootScope', 'contractCommonService', function ($rootScope, contractCommonService) {
        $rootScope.refundInfo = {};
        $rootScope.editInvoices = [];
        var service = {
            onRefundEditShow: function ($data, $dialog, $dialogScope, refundType, oldRefund,product_name) {
                $dialogScope.pname = product_name;

                console.log($dialogScope.data.qureyData);
                $dialogScope.total_pay_amount = 0;
                var contracts = $dialogScope.data.qureyData.itemsall;

                // 保留两位小数
                $dialogScope.total_pay_amount = $dialogScope.data.qureyData.totalpayamount.toFixed(2);

                $dialogScope.record_count = $dialogScope.data.qureyData.total;
                $dialogScope.beginDate = $dialogScope.data.qureyData.beginDate;
                $dialogScope.endDate = $dialogScope.data.qureyData.endDate;

                $dialogScope.FeeRates = {};

                $dialogScope.dhkItems = '';

                contractCommonService.getWithdrawFeeRate(function (data) {
                    $dialogScope.FeeRates = data;
                    $dialogScope.$applyAsync();
                });

                var self = this;
                $dialogScope.onRefundImportNoInvoiceShow = self.onRefundImportNoInvoiceShow;

                $dialogScope.importPayment = function (itemdhks) {
                    // 待录入回款信息回填
                    $('#unrecord-info').removeClass('hidden');
                    var items = [];
                    $.each(itemdhks, function (i,d) {
                        if(d.chkvalue && d.chkvalue == 1){
                            items.push(d);
                        }
                    });
                    items.sort(function(a,b){
                        return parseFloat(a.payment_amount) - parseFloat(b.payment_amount);
                    });

                    $dialogScope.refundInfoItems = items;
                    $dialogScope.dhkItems = items;

                    // 批量合同处理
                    $dialogScope.refundInfoList = [];
                    if (items.length>0) {
                        // 批量绑定回款
                        var contracts = $dialogScope.data.qureyData.itemsall;
                        var willProceMoney = 0;
                        var willDhkMoney = 0;
                        var curitem = null;

                        $.each(contracts, function (idx, d) {
                            var contract_id = d.contract_id;
                            if (contract_id != null) {
                                willProceMoney += parseFloat(d.pay_amount);
                                willDhkMoney = 0;
                                curitem = null;
                                for(var i=0;i<items.length;i++) {
                                    willDhkMoney += parseFloat(items[i].payment_amount);
                                    if (idx == 0) {
                                        curitem = items[0];
                                        break;
                                    } else {
                                        if (willProceMoney <= willDhkMoney) {
                                            curitem = items[i];
                                            break;
                                        }
                                    }
                                }
                                if(curitem == null){
                                    curitem = items[items.length-1];
                                }

                                var refundInfo;
                                $dialogScope.importPaymentAmount = curitem.payment_amount;//引入的回款金额
                                // copy item into refundinfo
                                refundInfo = angular.extend(angular.copy(curitem), {contract_id: contract_id},{payinfo_id:d.payinfo_id});
                                refundInfo.dhk_payment_amount = myMath.sub(refundInfo.payment_amount, refundInfo.have_payment_amount);
                                refundInfo.payment_amount = d.pay_amount;
                                var temp_input_date = refundInfo.payment_date;
                                refundInfo.input_date = util.formatDate(temp_input_date, 'yyyy-MM-dd');

                                refundInfo.receivables_account = $dialogScope.receivables_account;
                                refundInfo.receivables_account_name = $dialogScope.receivables_account_name;
                                refundInfo.pay_way = d.pay_way;
                                refundInfo.pay_way_fee_rate = $dialogScope.FeeRates[d.pay_way];

                                $dialogScope.refundInfoList.push(refundInfo);
                            };
                        });
                        console.log($dialogScope.refundInfoList);
                    } else {
                        util.alert('请选择回款记录');
                        return false
                    }
                };

                $dialogScope.contractBaseInfo = {contract_id: $data};
                //新建回款
                $dialogScope.refundInfo = {
                    contract_id: $data
                };

                //实收金额变更时，重新计算分摊金额
                $dialogScope.$watch('refundInfo.payment_amount', function () {
                    $dialogScope.shareAmount();
                });

                //分摊回款金额
                $dialogScope.shareAmount = function () {
                    var items = $dialogScope.editInvoicePayments || [];
                    var refundAmount = ($dialogScope.refundInfo.payment_amount || 0);
                    $.each(items, function (i, d) {
                        if (!d._checked || refundAmount <= 0) {
                            d.cur_payment_amount = 0;
                            return true;
                        }
                        d.cur_payment_amount = myMath.sub(d.cur_billing_amount, d.total_payment);
                        refundAmount -= d.cur_payment_amount;
                        if (refundAmount < 0) {
                            d.cur_payment_amount += refundAmount;
                        }
                    });
                };

                $dialogScope.orgianlRefund = oldRefund;
                $dialogScope.refundType = refundType;

                //下拉框设置

                //获取应收信息列表
                if (refundType == 1) {
                    //非查看模式取发票信息
                    contractCommonService.getInvoiceReceivableInfoByContract($data, function (json) {
                        $dialogScope.editInvoicePayments = json;
                        $dialogScope.$applyAsync();
                    });
                }

                console.log($dialogScope);
            },
            onRefundImportNoInvoiceShow: function ($dialogScope, importType, dialog) {
                /**
                 * 引入未开票回款界面初始化
                 */
                $dialogScope.selectedItems = [];
                $dialogScope.importPayments = [];
                $dialogScope.isloading = true;
                if (importType == 1) {
                    $dialogScope.importType = 1;//引入未开票回款
                    contractCommonService.getContractPaymentHaveAmountByContract($dialogScope.data.contract_id, function (data) {
                        $dialogScope.importPayments = data;
                        $dialogScope.isloading = false;
                        $dialogScope.$applyAsync();

                        setTimeout(function () {
                            dialog.reset();
                        }, 0);
                    })
                } else {
                    $dialogScope.importType = 2;//引入待录入回款
                    contractCommonService.getAccountHkList('', function (data) {
                        $dialogScope.importPayments = data;
                        $dialogScope.isloading = false;
                        $dialogScope.$applyAsync();


                        console.log($dialogScope.importPayments);
                        setTimeout(function () {
                            dialog.reset();
                        }, 0);
                    }, function () {
                        $dialogScope.isloading = false;
                        $dialogScope.$applyAsync();
                    });
                    $dialogScope.search = function (key) {
                        $dialogScope.isloading = true;
                        contractCommonService.getAccountHkList(key, function (data) {
                            $dialogScope.importPayments = data;
                            //console.log($dialogScope.importPayments);
                            $dialogScope.isloading = false;
                            $dialogScope.$applyAsync();
                        }, function () {
                            $dialogScope.isloading = false;
                            $dialogScope.$applyAsync();
                        });
                    }
                }

                $dialogScope.selectPayment = function (item, index) {
                    if(item.chkvalue && item.chkvalue == 1){
                        item.chkvalue = 0;
                        //$dialogScope.selectedItems.splice(item);
                    }else {
                        item.chkvalue = 1;
                        $dialogScope.selectedItems.push(item);
                    }
                };

                console.log($dialogScope);
            },
            editRefundSave: function ($data, $dialog, $dialogScope, callback, pname) {
                /**
                 * 保存新增回款
                 */
                if(pname != '云采购采宝'){
                    var refundInfoList = $dialogScope.refundInfoList;
                    var dhkItems = $dialogScope.dhkItems;
                    var datas = {
                        refundInfoList:refundInfoList,
                        dhkItems:dhkItems
                    };
                    service.confirmRefundSave(datas, $dialog, callback);
                }else{
                    $data['pname'] = pname;
                    service.confirmRefundSave($data, $dialog, callback);
                }
            },

            confirmRefundSave: function (post_data, $dialog, callback, options) {
                var url = api_prefix + "/receivable/save-contract-payment-by-many";

                util.myAjax({
                    url: url,
                    type: "POST",
                    context: this,
                    data: post_data,
                    async: false,
                    success: function (json) {
                        if (json.retCode == 0) {
                            util.alert("保存成功");
                            if (callback) {
                                callback();
                            }
                            $dialog.close();
                            location.reload();
                        } else {
                            util.alert("保存失败：" + json.errMsg);
                            return false;
                        }
                    }
                });

                return false;
            }
            ,
            deleteRefund: function (refundInfo, callback) {
                /**
                 * 删除回款
                 */
                util.confirm('确定要删除此回款吗?', {
                    ok: function () {
                        var post_data = {payment_id: refundInfo.payment_id, Dhk_id: refundInfo.DhkGUID};
                        var url;
                        url = api_prefix + "/receivable/delete-contract-payment";

                        util.myAjax({
                            url: url,
                            type: "POST",
                            context: this,
                            data: post_data,
                            success: function (json) {
                                if (json.retCode == 0) {
                                    refundInfo.__isdelete = 1;
                                    util.alert("删除成功");
                                    $rootScope.$applyAsync();
                                    if (callback) {
                                        callback();
                                    }
                                } else {
                                    util.alert("删除失败：" + json.errMsg);
                                }
                            }
                        });
                    }
                });
            }
        };

        return service;
    }]);

    module.exports = ContractReceivableRefund;
});